<?php

class myfb extends Facebook {

  protected static $_fb_page_id;
  protected static $_inst;
  protected $_signed_data;

  public static function getInst() {
    if (self::$_inst == NULL) {
      $config = array(
          'appId' => '167368716641811',
          'secret' => '8a5bbb54b3925e40a1b80e05a3da450e',
      );
      self::$_inst = new self($config);
    }
    return self::$_inst;
  }

  protected static function _getFacebookPageId() {
    if (@$_REQUEST['fb_page_id']) {
      return $_REQUEST['fb_page_id'];
    }
    $inst = self::getInst();
    return $inst->_getFacebookPageIdFromSignedData();
  }

  protected function _getFacebookPageIdFromSignedData() {
    if ($signed_request = @$_REQUEST['signed_request']) {
      $this->_signed_data = parent::getSignedRequest($signed_request);
    }
    if (@$this->_signed_data['profile_id']) {
      return $this->_signed_data['profile_id'];
    }
  }

  /**
   * return
   * get facebook page id
   * @return int(16)
   */
  public static function getFacebookPageId() {
    if (self::$_fb_page_id == NULL) {
      self::$_fb_page_id = self::_getFacebookPageId();
    }
    return self::$_fb_page_id;
  }

  public static function add($fb_app_id, $fb_page_id = NULL) {
    $fb_page_id = $fb_page_id ? $fb_page_id : self::getFacebookPageId();
    $data = array(
        'fb_page_id' => $fb_page_id,
        'fb_app_id' => (string) $fb_app_id,
        'created_time' => date('Y-m-d h:i:s'),
        'last_access_time' => date('Y-m-d h:i:s'),
    );
    $db = Db::factory();

    if ($db->insert('yns_myfb', $data)) {
      $myfb_id = $db->lastInsertId();
      Myfb_Render::setup($myfb_id, $fb_app_id);
      return $myfb_id;
    }
    return 0;
  }

  /**
   * get unique id combined ($fb_page_id, $fb_app)
   * @return int
   */
  public static function getId($fb_app_id, $fb_page_id = NULL) {
    $fb_page_id = $fb_page_id ? $fb_page_id : self::getFacebookPageId();
    $db = Db::factory();
    $sql = "select myfb_id from yns_myfb where fb_page_id = ? and fb_app_id = ?";

    if ($myfb_id = $db->fetchOne($sql, array($fb_page_id, $fb_app_id))) {
      return $myfb_id;
    }
    return self::add($fb_app_id, $fb_page_id);
  }

}